<?php
	include_once("backend/constant.php");
	$connection = new mysqli(dbhost, dblogin, dbpwd, database) or	die("Couldn't connect to database!");
	$connection->set_charset("utf8");
	$sql = "select a.id, u.username, a.createdDate, title_vn, abstract 
			from articles as a inner join users as u on a.userId=u.id 
			where a.active=1 order by a.createdDate desc";
	$postLst = $connection->query($sql) or die("Query failed!");
	session_start();
	//$fconfig = new DOMDocument();
	$pageView = 1;
	$sql = "select p_value from settings where p_name='pageview'";
	$result = $connection->query($sql) or die("Query failed select!");
	if($result!=false && $row=$result->fetch_assoc()){
		$pageView = $row["p_value"];
	}
	
	if(isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
		// last request was more than 30 minutes ago
		session_unset();     // unset $_SESSION variable for the run-time 
		session_destroy();   // destroy session data in storage
		
		if($pageView==1){
			$sql = "insert into settings(p_name, p_value) values('pageview', '" . $pageView . "')";
		}else{
			$pageView++;
			$sql = "update settings set p_value='" . $pageView . "' where p_name='pageview'";
		}
		$connection->query($sql) or die("Query failed!");
		
	}
	$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
	$_SESSION["page"]='index.php';
	
?>
<!DOCTYPE HTML>
<html>
	<head>
		<meta name="description" content="A web page to share programming concepts in Java, C/C++, Android">
		<meta charset="utf-8">
		<link rel="stylesheet" type="text/css" href="styles.css"/>
		<script type='text/javascript' src='jquery-min.js'></script>
		<script type="text/javascript">
			$(document).ready(function(){
				$("#btnLogin").click(function(){
					var username = document.getElementById("txtUsername").value;
					var pwd = document.getElementById("txtPassword").value;
					if(username.length <= 0){
						alert("Username cannot be blank");
						return false;
					}
					/*
					$.ajax({
						url:"backend/user.php",
						cache:false,
						type:'POST',
						data:{ACTION:'LOGIN',txtUsername:username,txtPassword:pwd},
						success:function(responseText){
							var rs = $.parseJSON(responseText);
							$('#div_login').fadeOut();
							$('#div_user_pane').hide().html("Login").fadeIn();
						}
					});
					*/
					$("#frmLogin").submit();
					return false;
				});
				
				$("#btnReg").click(function(){
					window.location.replace("reg.php");
					/*
						OR we can use
						window.location.href = "";
					*/
				});
				
				$("#btnLogout").click(function(){
					
					$.ajax({
						url:"backend/user.php",
						cache:false,
						type:'POST',
						data:{ACTION:'LOGOUT'},
						success:function(responseText){
							/*var rs = $.parseJSON(responseText);
							$('#div_user_pane').fadeOut();
							$('#div_login').fadeIn();*/
							window.location.replace("index.php");
						}
					});
					
					return false;
				});
				
				$("#btnSearch").click(function(){
					var kw = $("#txtSearch").val();
					$.ajax({
						url:"backend/post.php",
						cache:false,
						type:'POST',
						data:{ACTION:'SEARCH', keyword:kw},
						success:function(responseText){
							//alert(responseText);
							var rs = $.parseJSON(responseText);
							var newContent = "";
							//alert(rs.articles.length);
							if(rs.status == "OK"){
								//$("#div_main").html("");
								$.each(rs.articles, function() { 
									newContent = newContent + "<div><h3><a class='artc_title' href='article.php?id=" + (this.id) + "' >" + (this.title) + "</a></h3><p><span class='articleTime'>"+this.datetime+"</span> &nbsp;  by &nbsp;  <a href='#'><i>" + this.username + "</i></a></p></div>"+
									"<div>" + this.abstract + "</div><br/><hr/>";
								});
								$("#div_main").html(newContent);
							}
						}
					});
					
					return false;
				});
				
			});
			
		</script>
		
		<title>VTech blog - A technical blog</title>
	</head>
	<body>
		<div id="container">
			<div id="div_header">
				<?php 
					if( !isset($_SESSION["loggedUser"]) || $_SESSION["loggedUser"]==null){ ?>
				<div id="div_login">
					<form id="frmLogin" name="frmLogin" method="post" action="backend/login.php">
						<div style="float:left;width:120px;">
							<input type="hidden" name="ACTION" value="LOGIN" /> 
							<input style="width:79%;margin: 2px 25px;" type="text" class="loginText" id="txtUsername" name="txtUsername" value="" />
						</div>
						<div style="float:left;width:120px;">
							<input style="width:95%;margin: 2px 5px;" type="password" class="loginText" id="txtPassword" name="txtPassword" value="" />
						</div>
						<div style="float:left;padding-left:5px;vertical-align:middle;">
							<a href="#" style="text-decoration:none;color:#dafafa;" id="btnLogin">login</a> or <a style="text-decoration:none;color:#dafafa;" id="btnReg" href="#">sign up</a>
						</div>
					</form>
				</div>
				<?php }else{ ?>
					<div id="div_user_pane">
						<span style="padding-left:30px;color:#dafafa;">Xin chao </span>
						<a href="#" style="text-decoration:none;color:#ffff22;" ><span style="font-weight:bold;"><?php echo $_SESSION["loggedUser"]; ?></span></a>
						<a href="#" style="text-decoration:none;color:#ffdada" id="btnLogout">Logout</a>
						<!--
						<ul class="dropdown_menu">
							<li>
								<a href="#" style="text-decoration:none" ><?php echo $_SESSION["loggedUser"]; ?></a>
								<ul class="dropdown_menu_sub" style="list-style-type:none;">
									<li>
										<a href="#" style="text-decoration:none" id="btnAccount">Account</a>
									</li>
									<li>
										<a href="#" style="text-decoration:none" id="btnLogout">Logout</a>
									</li>
								</ul>
							</li>
						</ul>
						-->
					</div>
				<?php } ?>
			</div>
			<div id="div_nav" class="menu">
				<?php include "nav_bar.php" ?>
				<div style="position:absolute; top:103px; bottom:1px; right:30px; left:auto;">
					<input type="text" name="txtSearch" id="txtSearch" style="border: 1px solid #93A9C8;" />
					<input type="button" name="btnSearch" id="btnSearch" value="Search" />
				</div>
			</div>
			<div id="sidebar">
				<div>
					<?php
						$result = $connection->query("select id, title_vn from articles where active=1 order by nview desc limit 5") or die("Query failed select!");
						if($result != false){
							print "<ul class=\"popular-post\">";
							while($row = $result->fetch_assoc()){
								print "<li><a href=\"#\" id=\"post{$row["id"]}\" >" . $row["title_vn"] . "</a></li>";
							}
							print "</ul>";
						}
					?>
				</div>
				<div class="sidebar-tag">
					<?php
						$arrConstantTags = array(0=>'c/c++','java','javascript','uml','c#','algorithm',
						'vb','vba','linux','windows','android','mysql','atl','eclipse','rcp','computer-vision','php');
						$fontSize = 50;
						for($i=0;$i<count($arrConstantTags);$i++){
							$fontSize = rand(70, 100);
							print "<a href=\"#\" style=\"font-size:". $fontSize ."%;\"
							id=\"tag-item{$i}\" >" . $arrConstantTags[$i] . "</a>";
						}
					?>
				</div>
				<div id="pagehit">
					Page hits: <?php print $pageView; ?>
				</div>
			</div>
			<div id="div_main">
				<?php
					if($postLst != false){
						while($row = $postLst->fetch_assoc()){
							print "<div><h3><a class=\"artc_title\" href='article.php?id=" . $row["id"] . "'>" . $row["title_vn"] . "</a></h3>";
							print "<p><span class='articleTime'>" . $row["createdDate"]. "</span> &nbsp;  by &nbsp;  <a href='#'><i>" . $row["username"] . "</i></a></p></div>";
							print "<div>" . $row["abstract"] . "</div><br/><hr/>";
						}
					}
					$connection->close();
				?>
			</div>
			<div id="div_footer" >
				<div>Copyright 2013 @Dao Anh Vu</div>
			</div>
			
		</div>
	</body>
</html>
